<template>
  <div class="main_box" style="padding:10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ dataForm.modelId ? '编辑时间模板' : '新增时间模板' }}</h2>
        <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
      </div>
      <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules">
        <el-row>
          <el-form-item label="模板名称" prop="modelName">
            <el-input v-model="dataForm.modelName">

            </el-input>
          </el-form-item>
          <el-form-item label="商户" prop="businessId">
            <el-select v-model="dataForm.businessId" clearable filterable>
              <el-option v-for="item in businessList" :label="item.name" :value="item.id" :key="item.id">

              </el-option>
            </el-select>
          </el-form-item>
        </el-row>

        <el-row>
          <div class="tit">
            <h2>可售时间</h2>
            <el-button plain type="success" icon="el-icon-plus" circle @click="add()">

            </el-button>
          </div>
          <el-table :data="dataForm.relations" max-height="800" style="width:calc(100vw - 280px);max-width: calc(100vw - 280px);margin-top: 10px;">
            <el-table-column label="操作" align='center' width="80">
              <template slot-scope="scope">
                <el-button plain type="danger" icon="el-icon-minus" circle @click="sub(scope.$index)">

                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="可售时间段" agn="center" width="380">
              <template slot-scope="scope">
                <el-time-picker is-range v-model="scope.row.range" range-separator="至"
                value-format="HH:mm" format="HH:mm" :picker-options="{ format: 'HH:mm' }" start-placeholder="开始时间"
                  end-placeholder="结束时间" placeholder="选择时间范围">
                </el-time-picker>
              </template>
            </el-table-column>
            <el-table-column label="最快到达时间" align="center" width="480">
              <template slot-scope="scope">
                <el-time-picker v-show="scope.row.timeUnit==9" is-range v-model="scope.row.arriveTime1" range-separator="至"
                value-format="HH:mm" format="HH:mm" :picker-options="{ format: 'HH:mm' }" start-placeholder="开始时间"
                  end-placeholder="结束时间" placeholder="选择时间范围">
                </el-time-picker>
                <el-select style="width:350px" v-model="scope.row.arriveTime2" v-show="scope.row.timeUnit!=9" placeholder="请选择或输入时间" clearable filterable>
                  <el-option v-for="item in getTimeList(scope.row)" :key="item.time" :value="item.time" :label="item.time">

                  </el-option>
                </el-select>
                <!-- <el-input style="width:350px" v-show="scope.row.timeUnit!=9" placeholder="请输入时间" v-model="scope.row.arriveTime2" @input="handleTimeInput(scope.row)">

                </el-input> -->
                <el-select v-model="scope.row.timeUnit" placeholder="时间单位" @change="scope.row.arriveTime2 = ''">
                    <el-option label="分钟" :value="1"></el-option>
                    <el-option label="时" :value="2"></el-option>
                    <el-option label="时间段" :value="9"></el-option>
                  </el-select>
              </template>
            </el-table-column>
            <el-table-column label="可送达时间段(分)"  align="center" width="380">
              <template slot-scope="scope">
                <el-time-picker popper-class="delivery-time_picker"  is-range v-model="scope.row.deliveryTime" range-separator="至"
                    value-format="HH:mm" format="HH:mm" :picker-options="{ format: 'HH:mm' }" :disabledTime="disabledTime" start-placeholder="开始时间"
                  end-placeholder="结束时间" placeholder="选择时间范围">
                </el-time-picker>
              </template>
            </el-table-column>
            <el-table-column label="商户提醒时间(分)" align="center" width="150">
              <template slot-scope="{row}">
                <div>
                  <el-select v-model="row.businessRemindTime">
                    <el-option v-for="item in minutesList" :key="item.time" :value="item.time" :label="item.time">

                    </el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="服务员提醒时间(分)" align="center" width="150">
              <template slot-scope="{row}">
                <div>
                  <el-select v-model="row.waiterRemindTime">
                    <el-option v-for="item in minutesList" :key="item.time" :value="item.time" :label="item.time">

                    </el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>
          </el-table>

        </el-row>
        <el-row>
          <el-form-item>
            <el-button plain type="primary" @click="sureClick">保 存</el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import BusinessApi from "@/api/business/business";
import TimeTemplateApi from '@/api/goods/timeTemplate';
// import ServerClassifyApi from "@/api/server/serverClassify"
const TIME_LIST = []
for (let i = 0; i < 60; i++) {
  i!==0&&TIME_LIST.push({time:i})
}
export default {
  data() {
    return {
      dataForm: {
        modleId: "",
        modelName: "",
        businessId: "",
        relations: [
          {
            range:null,
            arriveTime1:null,
            arriveTime2:"",
            timeUnit:9, //1 表示分钟 2表示时 9表示时间段,
            deliveryTime:null,
            businessRemindTime:"",
            waiterRemindTime:"",
          }
        ],
      },
      minutesList:TIME_LIST,
      businessList: [],
      roleRules: {
        modelName: [
          { required: true, message: "请输入模板名称", trigger: "focus" }
        ],
        businessId: [
          { required: true, message: "请选择商户", trigger: "blur" }
        ]
      }
    }
  },
  components: {
  },
  mounted() {
    this.init()
  },
  methods: {
    disabledTime(val){
      console.log(1,val)
      return false
    },
    init() {
      this.getBusinessList()
      if (this.$route.query.id) {
        this.dataForm.modelId = this.$route.query.id
        this.getData()
      }
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    getData() {
      TimeTemplateApi.getTimeTemplateInfo({
        id: this.dataForm.modelId
      }).then(res => {
        this.$Utils.bindingBean(this.dataForm, res.data)
        const {relations} = this.dataForm
        this.dataForm.relations = relations.map(item=>{
          const arr = (item.estimateTime||"").split("-")
          return{
            range:[item.beginHours,item.endHours],
            arriveTime1:item.timeUnit==9?[arr[0],arr[1]||'']:null,
            arriveTime2:item.timeUnit!=9?arr[0]:'',
            deliveryTime:item.deliveryTime?item.deliveryTime.split("-"):null,
            timeUnit:item.timeUnit,
            businessRemindTime:item.businessRemindTime,
            waiterRemindTime:item.waiterRemindTime,
          }
        })
      })
    },
    getTimeList(row){
      const list = [
        {time:"1"},
        {time:"2"},
        {time:"3"},
        {time:"4"},
        {time:"5"},
        {time:"6"},
        {time:"7"},
        {time:"8"},
        {time:"9"},
        {time:"10"},
        {time:"11"},
        {time:"12"}
      ]

      return row&&row.timeUnit==2?list:this.minutesList
    },
    handleTimeInput(row){
      const reg = /[^0-9\:]|^\./g
      row.arriveTime2 = row.arriveTime2.toString().replace(/：/,":").replace(reg,"")
      const arr = row.arriveTime2.split("")
      if(arr.filter(item=>item==':').length>1){
        arr.splice(arr.lastIndexOf(':'),1)
        row.arriveTime2 = arr.join("")
      }
    },
    handleTimeUnitChange(row){
      row.arriveTime2 = ""
    },
    getBusinessList() {
      BusinessApi.listIdNameVo().then(res => {
        this.businessList = res.data
      })
    },
    add() {
      this.dataForm.relations.push({
            range:null,
            arriveTime1:null,
            arriveTime2:"",
            deliveryTime:null,
            timeUnit:9, //1 表示分钟 2表示时 9表示时间段,
          })
    },
    sub(index) {
      this.dataForm.relations.splice(index, 1)
    },
    checkData(){
      const {dataForm} = this
      dataForm.relations = dataForm.relations.filter(item=>item.range&&item.range[0])
      this.relations = dataForm.relations.map(item=>({
        beginHours:item.range[0],
        endHours:item.range[1],
        timeUnit:item.timeUnit,
        estimateTime:item.timeUnit==9?(item.arriveTime1?(item.arriveTime1[0]+"-"+item.arriveTime1[1]):''):item.arriveTime2,
        deliveryTime:item.deliveryTime?item.deliveryTime.join("-"):"",
        businessRemindTime:item.businessRemindTime,
        waiterRemindTime:item.waiterRemindTime,
      }))
      return true
    },
    sureClick() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          if(!this.checkData()) return
          this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {})
            .then(() => {
              if (this.dataForm.modelId) {
                this.editData();
              } else {
                this.addData();
              }
            });
        }
      })
    },
    addData() {
      let param = {
        modelName: this.dataForm.modelName,
        relations:this.relations,
        businessId:this.dataForm.businessId
      };
      TimeTemplateApi.addTimeTemplate(param).then(res => {
        this.$Utils.notifySuccess()
        this.returnList();
      })
    },
    editData() {
      let param = {
        modelId: this.dataForm.modelId,
        modelName: this.dataForm.modelName,
        relations:this.relations,
        businessId:this.dataForm.businessId
      };
      TimeTemplateApi.editTimeTemplate(param)
        .then(data => {
          this.$Utils.notifySuccess()
          this.returnList();
        })
    },
    returnList() {
      this.$store.dispatch('delView', this.$route);
      this.$router.push({ path: '/goods/timeTemplateManagement' });
    }
  },

}
</script>
<style lang="scss" scoped>
@import "@/assets/css/views/add.scss";
</style>
<style lang="scss">
.delivery-time_picker{
  // .el-time-spinner__item
  .el-time-spinner__wrapper:nth-of-type(2){
    // .el-time-spinner__item{
    //   display: none;
    // }
    .el-time-spinner__item:nth-of-type(15n){
      display: block;
    }
  }
}
</style>
<style lang="scss" scoped>
.el-select{
  width:100px;
}


.upload-img {
  &::v-deep .el-upload-dragger {
    display: flex;
    justify-content: space-around;
    align-items: center;

    .tip {
      padding-bottom: 30px;
    }
  }
}
</style>

